<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ip extends Finecms_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('ip2');
    }

	public function index()
	{


        if ($this->post('submit_del')) {
            foreach ($_POST as $var=>$value) {
                if (strpos($var, 'del_')!==false) {
                    $id = (int)str_replace('del_', '', $var);
                    $this->ip2->delete('id=' . $id);
                }
            }
            $this->adminMsg(dr_lang('操作成功'), dr_url('ip/index'), 3, 1, 1);
        }

        $ip       = $this->post('kw') ? $this->post('kw') : $this->get('ip');
        $page     = (int)$this->get('page');
        $page     = (!$page) ? 1 : $page;
        $pagelist = $this->instance('pagelist');
        $pagelist->loadconfig();
        $total    = $ip ? $this->ip2->count('ip', '`ip` LIKE "%' . $ip . '%"') : $this->ip2->count('ip');
        $pagesize = isset($this->site['SITE_ADMIN_PAGESIZE']) && $this->site['SITE_ADMIN_PAGESIZE'] ? $this->site['SITE_ADMIN_PAGESIZE'] : 8;
        $url      = dr_url('ip/index', array('page'=>'{page}', 'ip'=>$ip));
        $select   = $this->ip2->page_limit($page, $pagesize)->order(array('id DESC'));
        $data     = $ip ? $select->where('`ip` LIKE ?', '%' . $ip . '%')->select() : $select->select();
        $pagelist = $pagelist->total($total)->url($url)->num($pagesize)->page($page)->output();
        $this->template->assign(array(
            'list'  => $data,
            'pagelist' => $pagelist,
        ));
        $this->template->display('ip.html');
	}

    public function add() {

        if (IS_POST) {
            $data = $this->post('data');
            if (empty($data['ip'])) {
                $this->adminMsg(dr_lang('ip不能为空'));
            }
            if ($this->ip2->getOne('ip=?', $data['ip'])) {
                $this->adminMsg(dr_lang('ip不能重复'));
            }
            $data['addtime'] = time();
            $this->ip2->insert($data);
            $this->adminMsg(dr_lang('操作成功'), dr_url('ip/index'), 3, 1, 1);
        }
        $this->load->helper('fields');
        $this->template->display('ip_add.html');
    }

    public function edit() {
        $id   = (int)$this->get('id');
        $data = $this->ip2->find($id);
        if (empty($data)) $this->adminMsg(lang('a-aip-1'));
        if (IS_POST) {
            unset($data);
            $data = $this->post('data');
            if (empty($data['ip'])) $this->adminMsg(lang('a-aip-0'));
            if ($this->ip2->getOne('id<>' . $id . ' AND ip=?', $data['ip'])) $this->adminMsg(lang('a-aip-8'));
            $this->ip2->update($data, 'id=' . $id);
            $this->adminMsg(lang('success'), dr_url('ip/index'), 3, 1, 1);
        }
        $this->load->helper('fields');
        $this->template->assign('data', $data);
        $this->template->display('ip_add.html');
    }

}
